package ntu.metaweb.http;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;

import ntu.metaweb.Metaweb;
import ntu.metaweb.XMLMarshaller;
import ntu.metaweb.result.Comments;
import ntu.metaweb.result.LinkComments;
import ntu.metaweb.service.Service;
import ntu.metaweb.storage.WebPage;
import ntu.metaweb.storage.WebPageKey;
import ntu.metaweb.storage.WebPageQuery;
import ntu.metaweb.storage.WebPageQueryKey;
import ntu.p2p.dht.DHTContent;
import rice.Continuation;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;


@SuppressWarnings("restriction")
public class GetLinkCommentHandler implements CommandHandler {

	@Override
	public void handleCommand(final HttpExchange exchange,
			final HashMap<String, String> params) throws IOException {
		System.out.println("get link comment handler");
		if (params.get("from_url_parameter").equals("null"))
			params.put("from_url_parameter", "");
		if (params.get("to_url_parameter").equals("null"))
			params.put("to_url_parameter", "");
		final WebPageQueryKey fromKey = new WebPageQueryKey(
				URLDecoder.decode(params.get("from_url"), "UTF-8"), 
				URLDecoder.decode(params.get("from_url_parameter"), "UTF-8"));
		final URL toUrl = new URL(URLDecoder.decode(
				params.get("to_url") + params.get("to_url_parameter"), "UTF-8"));
		
		Metaweb.getInstance().getDhtApplication().lookup(fromKey, 
				new Continuation<DHTContent,Exception>() {

					@Override
					public void receiveException(Exception exception) {
					}

					@Override
					public void receiveResult(DHTContent result) {
						onReceiveResult(exchange, result, toUrl);
					}
		});
	}

	protected void onReceiveResult(HttpExchange exchange, DHTContent result, URL toUrl) {
		System.out.println("on receive result");
		WebPageQuery webpagequery = (WebPageQuery) result;
		LinkComments linkcomments = 
			new LinkComments(webpagequery.getOutLink().get(toUrl));
		byte[] temp = XMLMarshaller.getInstance().marshall(linkcomments).getBytes();
		System.out.println(XMLMarshaller.getInstance().marshall(linkcomments));

		try {
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/xml");

			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();
			responseBody.write(temp);
			responseBody.close();
			exchange.close();
			System.out.println("close get link comment handler");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

